package com.kongjs.application.controller.rest;

import com.kongjs.application.model.entity.Comments;
import com.kongjs.application.service.ICommentsService;
import com.kongjs.common.rest.annotation.Rest;
import jakarta.annotation.Resource;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@Rest
@RestController
@RequestMapping("/comments")
public class CommentsController {

    @Resource
    private ICommentsService commentsService;

    @PostMapping
    public void save(@RequestBody Comments comments){
        commentsService.save(comments);
    }

    @PatchMapping("/{id}")
    public void action(@PathVariable Long id, @RequestParam String action) {
        Optional<Comments> optionalComments = commentsService.getOptById(id);
        if (optionalComments.isPresent()) {
            Comments comments = optionalComments.get();
            if (StringUtils.hasText(action)) {
                if (action.equalsIgnoreCase("like")) {
                    if (ObjectUtils.isEmpty(comments.getCommentLikes())) {
                        comments.setCommentLikes(0L);
                    }
                    comments.setCommentLikes(comments.getCommentLikes() + 1L);
                    commentsService.updateById(comments);
                }
                if (action.equalsIgnoreCase("dislike")) {
                    if (ObjectUtils.isEmpty(comments.getCommentDislikes())) {
                        comments.setCommentDislikes(0L);
                    }
                    comments.setCommentDislikes(comments.getCommentDislikes() + 1L);
                    commentsService.updateById(comments);
                }
            }
        }
    }
}
